package cn.wolfcode.wolf2w.listener;

import cn.wolfcode.wolf2w.domain.Strategy;
import cn.wolfcode.wolf2w.redis.IStrategyRedisService;
import cn.wolfcode.wolf2w.redis.vo.StrategyStatisVO;
import cn.wolfcode.wolf2w.service.IStrategyService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class RedisDataInitListener implements ApplicationListener<ContextRefreshedEvent> {

    @Autowired
    private IStrategyService strategyService;
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private IStrategyRedisService strategyRedisService;

    // 当spring容器启动并初始化之后马上执行该方法
    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        System.out.println("初始化-----------------开始");

        // 从MongoDB中将数据搬出来 即 查询所有攻略
        List<Strategy> list = strategyService.list();
        // 遍历所有攻略,封装成vo对象
        for (Strategy strategy : list) {
            // 存在问题: 如果初始化之后,前端进行vo对象统计,
            // 缓存和数据中的数据不再一致,若我们再初始化,则会覆盖掉缓存里的数据
            // 结果方案: 判断vo是否存在,若存在则直接跳过
            if(strategyRedisService.isExist(strategy.getId())) {
               continue;
            }
            StrategyStatisVO vo = new StrategyStatisVO();
            BeanUtils.copyProperties(strategy, vo);
            vo.setStrategyId(strategy.getId());
            // 将vo对象缓存到redis中
            strategyRedisService.setStatisVo(strategy.getId(),vo);
        }
        System.out.println("初始化结束---------------");
    }
}
